package com.shenma2009.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 军哥
 * @version 1.0
 * @description: DeadLockDemo
 * @date 2023/6/27 10:21
 */

public class DeadLockDemo {

    public static Lock lock1 = null;
    public static Lock lock2 = null;

    public static void main(String[] args) {

        // 初始化锁
        lock1 = new ReentrantLock();
        lock2 = new ReentrantLock();

        // 创建线程
        Thread thread1 = new Thread(() -> {
            try {
                lock1.lock();//1

                Thread.sleep(3000);

                // want
                lock2.lock();//3->waiting
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock2.unlock();
                lock1.unlock();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                lock2.lock();//2

                Thread.sleep(3000);

                // want
                lock1.lock();//4->waiting
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
                lock2.unlock();
            }
        });

        // 运行线程
        thread1.setName("demo1");
        thread1.start();
        thread2.setName("demo2");
        thread2.start();

    }

}
